package com.example.audioreceiver;

import android.app.Service;
import android.content.Intent;
import android.media.AudioTrack;
import android.os.IBinder;
import android.os.Message;

import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;

public class AudioPlayService extends Service {
    private Thread thread;
    private boolean isStoped;
    private AudioTrack audioTrack;
    private DatagramSocket serverSocket;

    public AudioPlayService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        isStoped = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                runServerOnUDP();
            }
        });
        thread.start();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        isStoped = true;
        if (audioTrack != null) {
            int playState = audioTrack.getPlayState();
            if (playState == AudioTrack.PLAYSTATE_PLAYING || playState == AudioTrack.PLAYSTATE_PAUSED)
                audioTrack.stop();
            audioTrack.release();
        }
        if (serverSocket != null && !serverSocket.isClosed())
            serverSocket.close();
        Message message = new Message();
        message.obj = new String("destroy completed!\n");
        MainActivity.handler.sendMessage(message);
        super.onDestroy();
    }

    private void runServerOnTCP() {
        Message message = new Message();
        message.obj = new String("thread started!\n");
        MainActivity.handler.sendMessage(message);

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8086);
            while (!isStoped) {
                Socket socket = serverSocket.accept();

                message = new Message();
                message.obj = new String("accept data!\n");
                MainActivity.handler.sendMessage(message);

                InputStream inputStream = socket.getInputStream();
                byte buffer[] = new byte[1024 * 4];
                int temp = 0;
                while ((temp = inputStream.read(buffer)) != -1) {
                    message = new Message();
                    message.obj = new String(buffer);
                    MainActivity.handler.sendMessage(message);
                }
            }
            message = new Message();
            message.obj = new String("completed!\n");
            MainActivity.handler.sendMessage(message);
            serverSocket.close();
        } catch (IOException e) {

        }
    }

    private void runServerOnUDP() {
        Message message = new Message();
        message.obj = new String("thread started!\n");
        MainActivity.handler.sendMessage(message);

        audioTrack = AudioTrackManager.getInstance().getAudioTrack();
        audioTrack.play();

        try {
            serverSocket = new DatagramSocket(8086);
            byte[] temp = new byte[4];
            byte buffer[] = new byte[1024 * 8];

            while (!isStoped) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                serverSocket.receive(packet);

                byte[] tempData = packet.getData();

                temp[0] = tempData[0];
                temp[1] = tempData[1];
                temp[2] = tempData[2];
                temp[3] = tempData[3];

                int length = byteToInt(temp);

                audioTrack.flush();
                audioTrack.write(packet.getData(), 4, length);
            }
            message = new Message();
            message.obj = new String("thread stoped!\n");
            MainActivity.handler.sendMessage(message);

            serverSocket.close();
            audioTrack.stop();
            audioTrack.release();
        } catch (IOException e) {

        }
    }

    private int byteToInt(byte[] bytes) {
        return  bytes[0] & 0xFF |
                ((bytes[1] & 0xFF) << 8) |
                ((bytes[2] & 0xFF) << 16) |
                ((bytes[3] & 0xFF) << 24);
    }
}
